<template>
  <div id="app">
    <head-nav></head-nav>
    <head-search  v-if="!isShowSearch" :shopHide="shopHide"></head-search>
    <div class="main" :style="{height: loginHeight }">
      <router-view></router-view>
    </div>
    <mainRight v-if="needHiddenRight"></mainRight>
    <footer-nav></footer-nav>
    <!-- 合并 认证失败 ||未认证-->
     <el-dialog title="" class="index-dialog-wrapper" :visible.sync="certvisi" width="480px" :before-close="handleClose" center>
      <div class="dialog-certinfo-wrapper">
        <template v-if="infoViewVisi">
          <p class="info-content">亲爱的用户，您的账号存在安全风险<br>
          为了账号安全，请上传企业信息</p>
          <span class="small-content">完善企业信息之后将获得优惠折扣券</span>
        </template>
        <template v-else>
          <p class="info-content">亲爱的用户，由于您的账号未通过审核<br>将无法使用网站完整功能</p>
          <span class="small-content">请重新上传审核资料</span>
        </template>
        
      </div>
      <span slot="footer" class="dialog-footer">
        <span class="btn-submit" @click="uploadCompanyInfo()">立即上传</span>
      </span>
    </el-dialog>
    <!-- 审核结果 -->
    <el-dialog title="" class="index-dialog-wrapper exam-wrapper txt-center" :visible="examresult_status" width="480px" @close="closeDialog" :show-close="true" top="20vh">
      <div class="dialog-certinfo-wrapper">
        <p class="info-content" v-if="loginStatus === 3">您还未提交审核信息，请尽快提交企业信息</p>
        <div class="exam-box" v-else>
          <p class="title">当前审核结果</p>
          <p class="content" :class="{'marbt-60': loginStatus === 0 || loginStatus === 1}">{{examTypes[loginStatus]}}</p>
          <p class="reason" v-if="loginStatus === 2">{{examRecordList.length ? examRecordList[0].auditReason : '营业执照太模糊'}}</p>
        </div>
      </div>
      <router-link :to="{name: 'CompanyCert'}" 
        @click.native="$store.state.examine.examresultbox = false" 
        class="btn-submit" 
        v-if="loginStatus === 3 || loginStatus === 2">
          {{loginStatus === 3 ? '提交审核' : '重新提交审核'}}
      </router-link>
      <div class="exam-record-box">
        <p class="title">审核记录</p>
        <p v-if="!examRecordList.length">暂无</p>
        <template v-for="(item, index) in examRecordList" v-else>
          <p class="content">{{item.createTime}} <span class="pad-lf-10">{{item.auditStatus}}</span></p>
        </template>
      </div>
    </el-dialog>
    <!-- 用户手机号是否绑定手机号 popMobileVisi-->
    <el-dialog title="" class="index-dialog-wrapper mobile-dialog-wrapper txt-center" :visible="popMobileVisi" @close="bindMobileFn" width="480px" top="20vh">
      <div class="dialog-mobile-wrapper" v-if="mobile_one">
        <p class="info-content">尊敬的用户<br>刀具联盟系统升级需验证手机号</p>
        <p class="small-tit">请尽快完成验证</p>
        <span class="btn-submit" @click="mobile_one = false, mobile_two = true">立即验证</span>
      </div>
      <div class="dialog-mobile-wrapper" v-else-if="mobile_two">
        <div class="form-item">
          <input v-model="mobile" class="form-input el-input__inner" type="text" ref='mobile' @focus="mobileErrText = ''" placeholder="请输入11位手机号码"/>
        </div>
        <div class="form-item" style="margin-bottom: 0;">
          <div class="validate-box">
            <input v-model="imgVerifyCode" 
              class="form-input el-input__inner left"
              style="width: 246px" type="text"
              auto-complete="off"
              placeholder="请输入图形验证码"
             ref="refcode" 
             @focus="mobileErrText = ''"/>
            <img
              :class="{'valicode-item imgCode': true}"
              @click="getCode"/>
          </div>
        </div>
        <div class="form-item" style="margin-bottom: 0;">
          <div class="validate-box">
            <input v-model="code" 
              class="form-input el-input__inner left"
              style="width: 246px" type="text"
              auto-complete="off"
              placeholder="请输入6位验证码"
             ref="refcode" 
             @focus="mobileErrText = ''"/>
            <button
              :class="{'valicode-item valiCode': true, 'disabled': isSend}"
              @click="getCode"> {{validateText}}</button>
          </div>
        </div>
        <p class="error" v-show="mobileErrText">{{mobileErrText}}</p>
        <span class="btn-submit" @click="modifyMobile">确认验证</span>
      </div>
      <div class="dialog-mobile-wrapper" v-else>
        <p class="info-content">恭喜您验证成功</p>
        <p class="small-tit">祝您采购成功</p>
        <router-link :to="{name: 'Index'}" class="btn-submit" @click.native="bindMobileFn">前往首页</router-link>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { PHONE } from '@/config/regex'
import { Dialog, Button } from 'element-ui'
import { headSearch, headNav, footerNav, mainRight } from './components/index'
import { mapState, mapActions, mapGetters } from 'vuex'
import { eventBus } from './tool/events-bus'
import { postFeedback, activityJoinLog, auditLogList, sendCode, modifyMobile, verifyImage } from '@/service/get-data'
import { getCookie, clearCookie, setStore } from '@/config/mUntils'
import { examTypes } from '@/tool/index'
import Jsonp from 'jsonp'
import { judgeWareHouseIdMixin } from '@/mixins'
// setCookie
export default {
  name: 'app',
  components: {
    headNav,
    headSearch,
    mainRight,
    footerNav,
    elDialog: Dialog,
    elButton: Button
  },
  mixins: [judgeWareHouseIdMixin],
  data () {
    return {
      examTypes,
      // popMobileVisi: this.$store.state.user.bindMobilePop && !this.certvisi, // certvisi认证弹窗
      needHiddenRight: true,
      mobile_one: true,
      mobile_two: false,
      enterVisible: true,
      infoViewVisi: false,
      opinionVisi: false,
      feedtext: '',
      info: false, // 完善信息 数据返回
      toName: '', // 当前的name
      loginHeight: 'auto',
      shopback: false,
      examRecordList: [],
      mobile: '', // 注册手机号码
      code: '', // 短信验证码
      imgVerifyCode: '', // 图形验证码
      codeImg: '', // 图形验证码base64
      mobileError: { // 手机号码验证
        status: false,
        text: []
      },
      mobileErrText: '', // 提交号码后台返回提示错误
      time: 0,
      codeError: { // 验证码
        status: false,
        text: []
      },
      isSend: false, // 短信是否发送
      strategy: {
        mobile: {
          zero: '手机不能为空',
          rules: [PHONE],
          texts: ['手机格式不正确']
        },
        code: {
          zero: '请填写验证码',
          rules: [/^\d{6}$/],
          texts: ['长度为6']
        }
      },
      citycode: '' // 城市code
    }
  },
  computed: {
    ...mapState({
      isShowSearch: state => {
        return state.hiddenSearch
      },
      shopHide: state => {
        return state.shopcartHide
      },
      shopcartback: state => {
        return state.shopcartback
      },
      exam_failure: state => {
        return state.examine.exam_failure
      },
      exam_nodo: state => {
        return state.examine.exam_nodo
      },
      exam_index: state => {
        return state.examine.is_index_exam
      },
      isLogin: state => {
        return state.user.isLogin
      },
      shopcartnum: state => state.shopcart.shopcartnum,
      activityId: state => state.activityId - 0,
      examresult_status: state => state.examine.examresultbox,
      Exam: state => state.user.isExam - 0
    }),
    ...mapGetters(['loginStatus']),
    Token () {
      return getCookie('Token')
    },
    popMobileVisi () {
      return this.$store.state.user.bindMobilePop && !this.certvisi
    },
    textLen () {
      return this.feedtext.length
    },
    showActivity () {
      let result = this.toName === 'Login' || this.toName === 'Register' || this.toName === 'CompanyCert'
      return !result
    },
    certvisi () {
      return this.infoViewVisi || this.exam_failure
    },
    ableSendCode () {
      return this.isSend && this.imgVerifyCode !== ''
    },
    validateText () {
      return this.time > 0 ? this.time + 's' : '获取验证码'
    }
  },
  methods: {
    ...mapActions(['fetchActivityId', 'fetchWarehouseId']),
    // ip获取citycode
    getPositionCode () {
      Jsonp('https://restapi.amap.com/v3/ip', { param: 'key=db587dabed4b706d517bd06c10ab5dba&callback' }, (err, data) => {
        if (err) {
          console.error(err.message)
        } else {
          data.status === '1' ? this.positonAreaCode = data.adcode : this.positonAreaCode = ''
          this.$store.state.IPCode = this.positonAreaCode
          this.judgeWareHouseId() // 获取分仓id
        }
      })
    },

    closeDialog () {
      this.$store.state.examine.examresultbox = false
    },

    // 审核记录
    async fetchAuditLogList () {
      let res = await auditLogList()
      if (res.data.resultCode && res.data.resultCode === 2000) {
        this.examRecordList = res.data.data
      }
    },

     // 活动日志
    async setLog (text) {
      let res = await activityJoinLog(this.username, this.activityId, text)
      if (res.data.resultCode && res.data.resultCode === 2000) {
      } else {
        this.$message(res.data.resultMsg || '网络出错')
      }
    },

    clickShopcart () {
      if (!this.Token) return
      let actions = new Map([
        [1, () => {
          this.$refs.floatShopRef.className = 'float-shop-pop'
          this.$router.push({name: 'ShopCart'})
          this.shopback = true
        }],
        [3, () => {
          this.$store.commit('EXAMNODO', true)
        }],
        [2, () => {
          this.$store.commit('EXAMFAIL', true)
        }],
        ['default', () => {
          this.$message.error('您的企业信息还在审核中,商品不能加入购物车,我们尽快给您审核.')
        }]
      ])
      let event = actions.get(this.Exam) || actions.get('default')
      event.call(this)
    },

    // 完善企业信息
    uploadCompanyInfo () {
      let type = this.exam_failure ? 'fail' : 'nodo'
      const actions = {
        'nodo': () => { this.$store.commit('EXAMNODO', false) },
        'fail': () => { this.$store.commit('EXAMFAIL', false) }
      }
      let action = actions[type]
      action.call(this)
      this.$router.push({name: 'CompanyCert'})
    },
    // 查看审核失败原因
    readExamReason () {
      this.examfailshow = false
      this.$router.push({name: 'ComCertUploadResult', params: {type: 'failure'}})
    },
    handleClose () {
      let type = this.exam_failure ? 'fail' : 'nodo'
      this.$confirm('为了您的账号安全，您确定暂时不去完善填写企业信息吗?').then(_ => {
        if (type === 'nodo') {
          this.$store.commit('EXAMNODO', false)
        } else if (type === 'fail') {
          this.$store.commit('EXAMFAIL', false)
        }
        // done()
      }).catch(_ => {})
    },
    showAlert (text) {
      this.$alert(text)
    },
    async submitFeed () {
      let res = await postFeedback(this.feedtext)
      if (res.data.resultCode && res.data.resultCode === 2000) {
        this.$message({
          message: '反馈提交成功，刀具联盟感谢您的支持!',
          duration: 2000,
          type: 'success'
        })
        this.opinionVisi = false
        this.feedtext = ''
      } else {
        this.$message({
          message: res.data.resultMsg,
          duration: 2000,
          type: 'error'
        })
        this.feedtext = ''
      }
    },
     // 验证表单字段
    validateMethod (value, type) {
      // debugger
      let strategy = this.strategy
      let error = type + 'Error'
      let zero = strategy[type]['zero']
      let rules = strategy[type]['rules']
      let texts = strategy[type]['texts']
      this[error].text = []
      if (value.length < 1) {
        this[error].status = false
        !zero ? this[error].text.push() : this[error].text.push(zero)
        return false
      }
      this[error].status = true
      // 不存在 rules
      if (!rules) return
      for (let i = 0; i < rules.length; i++) {
        if (!rules[i].test(value)) {
          this[error].status = false
          this[error].text.push(texts[i])
        }
      }
    },
    // 获取图形验证码
    async verifyImage () {
      let res = await verifyImage()
      if (res.status === 200) {
        var windowUrl = window.URL || window.webkitURL // 处理浏览器兼容性
        this.codeImg = windowUrl.createObjectURL(res.data)
      }
    },
    // 发送短信验证码
    async getCode () {
      if (!PHONE.test(this.mobile)) {
        this.mobileErrText = '请填写正确的手机号码'
        return
      }
      // this.time = 60
      if (this.time !== 0 || this.isSend) {
        return
      }
      let res = await sendCode(this.mobile, 0, this.imgVerifyCode)
      if (res.data.resultCode && res.data.resultCode !== 2000) {
        this.verifyImage() // 重新获取验证码
        this.$message({
          message: res.data.resultMsg,
          type: 'error'
        })
        if (res.data.resultCode === 6000) {
          this.$refs.mobile.focus()
        }
      } else {
        this.time = 60
      }
    },
    // 修改手机号接口,换成新手机号
    async modifyMobile () {
      if (!this.mobile || !this.code) {
        return
      }
      let res = await modifyMobile(this.mobile, this.code)
      if (res.data.resultCode && res.data.resultCode === 2000) {
        this.mobile_one = false
        this.mobile_two = false
        this.mobileErrText = ''
      } else {
        this.mobileErrText = res.data.resultMsg
      }
    },
    bindMobileFn () {
      this.mobile = ''
      this.code = ''
      this.mobile_one = true
      this.mobile_two = false
      this.$store.commit('BINDMOBILE', false)
    },
    // TODO: 活动时间
    activityStartTime () { // activeStatus 未开始 0 进行中 1 已结束 2
      const startD = '2019/05/15 00:00:00'
      const endD = '2019/05/15 24:00:00'
      // startTimeParm.replace(/-/g, '/')
      const startDstamp = new Date(startD).getTime()
      const endDstamp = new Date(endD).getTime()
      const nowStamp = new Date().getTime()
      if (nowStamp < startDstamp) {
        // console.log('活动未开始')
        this.$store.commit('ACTIVESTATUS', 0)
      }
      if (nowStamp > endDstamp) {
        // console.log('活动已结束')
        this.$store.commit('ACTIVESTATUS', 2)
      }
      if (nowStamp >= startDstamp && nowStamp <= endDstamp) {
        // console.log('活动进行中')
        this.$store.commit('ACTIVESTATUS', 1)
      }
    },
    exit () {
      clearCookie('septActivityDate')
      this.$store.commit('EXIT', true)
      this.$store.state.shopcart.cartlist = []
      this.$store.state.shopcart.shopCartId = ''
      this.$router.push({name: 'Login'})
    }
  },
  mounted () {
    setStore('warehouseId', 1)
    this.fetchActivityId()
    // this.activityStartTime()
    // this.getPositionCode() // 用户ip地址获取城市码
    // todo 订阅事件
    eventBus.$on('show:alert', (text) => {
      this.showAlert(text)
    })
  },
  watch: {
    '$route' (to, from) {
      this.needHiddenRight = true
      this.toName = to.name
      if (to.name === 'Register') {
        this.needHiddenRight = false
      }
      if (to.name === 'Login') {
        let clientH = document.body.clientHeight
        this.loginHeight = (clientH - 262) + 'px'
        this.needHiddenRight = false
      } else {
        this.loginHeight = 'auto'
      }
      if (to.name === 'Index') {
        this.$store.commit('ISINDEXEXAM', 1)
      } else {
        this.$store.commit('ISINDEXEXAM', 0)
      }
    },
    time (newV, oldV) {
      let t
      if (newV <= 0) {
        clearTimeout(t)
        this.time = 0
        this.isSend = false
      } else {
        this.isSend = true
        t = setTimeout(() => {
          this.time--
        }, 1000)
      }
    },
    // 计算反馈信息的字数
    feedtext (newval) {
      if (newval.length + 1 > 250) {
        this.$message({
          message: '字数最多250个',
          type: 'danger'
        })
        this.feedtext = this.feedtext.substring(0, 250)
      }
    },
    exam_nodo (newval) {
      let needUpdateStatus = getCookie('needUpdateStatus') === 'true'
      let examStatus = getCookie('Exam') === '3'
      let result = (needUpdateStatus || examStatus) && this.exam_nodo
      this.infoViewVisi = result
    },
    examresult_status (newval) {
      if (this.examresult_status) {
        this.fetchAuditLogList()
      }
    }
  }
}
</script>

<style lang="scss">
  @import './style/base.scss';
  @import './style/common.scss';
  html,body{
    background: #F8F8F8;
    height:100%;
  }
  .clearfix:before, .clearfix:after {
    content: " ";
    display: table;
}
  .fl{
    float: left;
  }
  .fr{
    float: right;
  }
  #app{
    // display: flex;
    // flex-direction: column;
    background: #fff;
    height:100%;
  }
  .main-all{
    // padding-right: 60px;
    position: relative;
  }
  .main-left{
    overflow: hidden;
  }
  .main{
    position: relative;
    background: #F8F8F8;
    min-height: 600px;
    overflow: hidden;
  }
  .text-box{overflow:hidden;margin-bottom:10px;}
  .textarea_con {
      box-sizing: border-box;
      width: 100%;
      outline: none;
      padding: 10px;
      border: 1px solid #DDDDDD;
      border-radius: 2px;
    }
  .submitBtn{
    float: right;
    width: 120px;
    color: #444444;
  }
  .word_num{
    margin-top:10px;
    font-size: 14px;
    color: #999999;
    line-height: 30px;
    em{
      color: #2A2A2A;
    }
  }
 .el-dialog__title{
    font-size: 14px;
  }
  .el-dialog__body{
    padding: 4px 14px;
  }
  // activity

  .activity-box{
    position: relative;
    width: 485px;
    margin: 15% auto 0;
    height: 460px;
    .btn-close{
      position: absolute;
      top:10px;
      right:10px;
      color: rgb(202, 202, 202);
      // text-shadow: #f1eded 0 0 4px;
      // -webkit-text-stroke:1px #dedede;
      font-size: 1.5rem;
    }
  }
  .activity-img{
    img{
      width: 100%;
    }
  }
  .v-modal{
    opacity: 0.7!important;
  }
  .info-content{
    font-weight: 600;
    line-height: 1.5;
    margin-bottom: 15px;
    font-size: 18px;
    color: #303030;
  }
  .dialog-certinfo-wrapper{
    text-align: center;
    .small-content{
      color: #6B6B6B;
    }
  }
  .btn-submit{
    font-family:PingFangSC-Regular;
    display: inline-block;
    padding: 12px 0;
    width: 200px;
    text-align: center;
    border-radius: 5px;
    color: #303030;
    background: #FFE100;
    font-size: 16px;
    cursor: pointer;
  }
  // 抽奖
  .luck-box{
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    /* background: #fff; */
    top: 100px;
    z-index: 2003;
  }
  .luck-wrapper{
    width: 400px;
    border-radius: 10px;
    background: #fff;
    overflow: hidden;
    .gift_left{
      position: absolute;
      left: -54px;
      top: -44px;
      width: 40px;
    }
    .gift_right{
      position: absolute;
      right: -54px;
      top: -74px;
      width: 95px;
    }
  }
  .luck-content{
    background: #FFE100;
    text-align: center;
    .close-text{
      font-size: 20px;
      position: absolute;
      right: 8px;
      top: 8px;
      font-weight: 600;
      cursor: pointer;
    }
    .title{
      font-size: 22px;
      color: #303030;
      line-height: 30px;
      padding-bottom: 10px;
    }
    .content{
      font-size: 16px;
      color: #6B6B6B;
      line-height: 25px;
      padding-bottom: 25px;
    }
  }
  .luck-top{
    padding: 60px 16px 15px;
  }
  .luck-num-box{
    width: 100%;
    background: url('./images/gift_bg.png') no-repeat;
    background-size: contain;
    height: 150px;
    padding-top: 35px;
    margin-top: 20px;
    .number{
      font-size: 50px;
      color: #EA1F1F;
      font-weight: 600;
      /* padding-bottom: 5px; */
      line-height: 1.1;
    }
    .small-tag{
      font-size: 40px;
    }
    .desribe{
      font-size: 14px;
      color: #6B6B6B;
      padding-bottom: 14px;
    }
    .effectivedate{
      font-size: 14px;
      color: #BBBBBB;
    }
  }
  .luck-button-box{
    padding: 30px 0;
    background: #fff;
    cursor: pointer;
    .btn-order{
      background: #EA1F1F;
      border-radius: 5px;
      font-size: 18px;
      color: #FFFFFF;
      width: 200px;
      height: 50px;
      line-height: 50px;
      display: inline-block;
    }
  }
  .index-dialog-wrapper{
    .el-dialog{
      border-radius: 10px;
    }
    .el-dialog__headerbtn .el-dialog__close{
      color: #303030;
      font-weight: bolder;
    }
    .el-dialog__body{
      padding: 25px 0 0 0;
      text-align: center!important;
    }
  }
  .exam-record-box{
    border-top: 1.5px dashed #e8e8e8;
    padding: 20px 0 20px 29px;
    text-align: left;
    .title{
      font-size:18px;
      font-family:PingFangSC-Regular;
      color:rgba(51,51,51,1);
      line-height:25px;
      margin-bottom: 12px;
    }
    .content{
      color: #6B6B6B;
      line-height:20px;
      margin-bottom: 10px;
      font-size:14px;
      &:last-child{
        margin-bottom: 0;
      }
    }
  }
  .pad-lf-10{
    padding-left: 10px;
  }
  .dialog-mobile-wrapper{
    .el-input__inner{
      height: 50px;
    }
  }
</style>
<style lang="scss" scoped>
  .marbt-60{
    margin-bottom: 60px;
  }
  .exam-box{
    .title{
      font-family:PingFangSC-Regular;
      margin-bottom: 22px;
      color: #999999;
      font-size:18px;
      line-height: 25px;
    }
    .content{
      font-family:PingFangSC-Medium;
      font-size:26px;
      font-weight:500;
      color:rgba(51,51,51,1);
      line-height:37px;
    }
    .reason{
      font-family:PingFangSC-Regular;
      font-size:16px;
      font-weight:400;
      color:rgba(255,0,0,1);
      line-height:22px;
    }
  }
  .exam-wrapper{
    .btn-submit{
      font-family:PingFangSC-Regular;
      margin-top: 30px;
      margin-bottom: 26px;
    }
  }
  .mobile-dialog-wrapper{
    padding-bottom: 30px;
    .small-tit{
      margin-bottom: 30px;
      font-size: 16px;
      line-height: 22px;
    }
  }
  .dialog-mobile-wrapper{
    padding: 0 55px 40px;
    .info-content{
      font-size: 20px;
    }
    .form-item{
      padding-bottom: 15px;
      overflow: hidden;
    }
    .btn-submit{
      width: 100%;
      margin-top: 15px;
    }
    .error{
      text-align: left;
      color: #ff0000;
      font-size: 12px;
      margin-top: -15px;
    }
  }
  .validate-box{
    position: relative;
    overflow:hidden;
    .valicode-item{
      position: absolute;
      right: 2px;
      top: 0;
    }
  }
  .valiCode{
    width: 122px;
    // height: 40px;
    border: none;
    line-height: 50px;
    text-align: center;
    padding: 0 4px;
    font-size:14px;
    color:#9B3F02;
    background: rgba(236, 116, 0, 0.6);
    border-radius: 3px;
    cursor:pointer;
    &.disabled {
      color:#bdbdbd;
      background-color: #f0f0f0;
    }
  }
</style>
